package com.pwx.student.interceptor;

import com.alibaba.druid.util.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pwx.student.common.Const;
import com.pwx.student.common.ResponseCode;
import com.pwx.student.common.ResponseResult;
import com.pwx.student.utils.TokenUtils;
import com.pwx.student.vo.output.LoginOutputVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Copyright (C),2021-2022,亚瑟王
 * FileName: MyAuthorizationInterceptor
 * Author: saber
 * Date:2022/10/27 11:05
 */
public class MyAuthorizationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        response.setContentType("applicaton/json;charset=utf-8");
        HttpSession session = request.getSession();

        String method = request.getMethod();
        if("OPTIONS".equals(method)){
            return true;
        }

        String token = request.getHeader("Authorization");

        ObjectMapper om = new ObjectMapper();

        LoginOutputVo login = (LoginOutputVo) session.getAttribute(Const.IS_LOGIN);


        if (login==null||StringUtils.isEmpty(token)){

            ResponseResult<String> rr = new ResponseResult<String>(
                    ResponseCode.IS_NOT_LOGIN.getCode(),"没有登录无法访问",null);

            response.getWriter().println(om.writeValueAsString(rr));
            return false;
        }

        try {
            Claims claims = TokenUtils.parseToken(token);

            String jti =(String) claims.get("jti");

            if (!jti.equals(login.getUserId().toString())){

                ResponseResult<String> rr = new ResponseResult<String>(
                        ResponseCode.IS_NOT_LOGIN.getCode(),"登入失败请重新登录，或者联系管理员",null);

                response.getWriter().println(om.writeValueAsString(rr));
                return false;
            }

            return true;
        } catch (ExpiredJwtException e) {
            e.printStackTrace();
            ResponseResult<String> rr = new ResponseResult<String>(
                    ResponseCode.IS_NOT_LOGIN.getCode(),"令牌已过期请重新登录",null);
            //写出前端
            response.getWriter().println(om.writeValueAsString(rr));
        } catch (Exception e) {
            e.printStackTrace();
            ResponseResult<String> rr = new ResponseResult<String>(
                    ResponseCode.IS_NOT_LOGIN.getCode(),"服务器异常",null);
            //写出前端
            response.getWriter().println(om.writeValueAsString(rr));
        }
        return false;
    }
}
